/**
 * Tool List Component
 * 
 * Displays all available tools from MCP servers
 */

import { useState, useEffect } from 'react';
import { Wrench, RefreshCw, ChevronDown, ChevronUp } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import type { Tool } from '@/api/mcp';
import * as mcpApi from '@/api/mcp';

export function ToolList() {
  const [tools, setTools] = useState<Tool[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [expandedTools, setExpandedTools] = useState<Set<string>>(new Set());

  const loadTools = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await mcpApi.listTools();
      setTools(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load tools');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadTools();
  }, []);

  const toggleTool = (toolName: string) => {
    setExpandedTools((prev) => {
      const next = new Set(prev);
      if (next.has(toolName)) {
        next.delete(toolName);
      } else {
        next.add(toolName);
      }
      return next;
    });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <RefreshCw className="w-6 h-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold">可用工具</h2>
          <p className="text-sm text-muted-foreground">
            查看所有已注册的工具和它们的参数
          </p>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={loadTools}
        >
          <RefreshCw className="w-4 h-4 mr-2" />
          刷新
        </Button>
      </div>

      {/* Error Message */}
      {error && (
        <Card className="border-destructive">
          <CardContent className="pt-6">
            <div className="text-destructive">{error}</div>
          </CardContent>
        </Card>
      )}

      {/* Tool List */}
      {tools.length === 0 ? (
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-8 text-muted-foreground">
              <Wrench className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>暂无可用工具</p>
              <p className="text-sm mt-2">
                添加 MCP 服务器后，工具将自动显示在这里
              </p>
            </div>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-3">
          {tools.map((tool) => {
            const isExpanded = expandedTools.has(tool.name);
            return (
              <Card key={tool.name} className="overflow-hidden">
                <CardHeader className="pb-3">
                  <div
                    className="flex items-start justify-between cursor-pointer"
                    onClick={() => toggleTool(tool.name)}
                  >
                    <div className="space-y-1 flex-1">
                      <div className="flex items-center gap-2">
                        <Wrench className="w-4 h-4" />
                        <CardTitle className="text-base">{tool.name}</CardTitle>
                        <Badge variant="outline" className="text-xs">
                          工具
                        </Badge>
                      </div>
                      <CardDescription className="text-sm">
                        {tool.description}
                      </CardDescription>
                    </div>
                    <Button variant="ghost" size="icon" className="h-8 w-8">
                      {isExpanded ? (
                        <ChevronUp className="w-4 h-4" />
                      ) : (
                        <ChevronDown className="w-4 h-4" />
                      )}
                    </Button>
                  </div>
                </CardHeader>

                {isExpanded && (
                  <CardContent className="pt-0">
                    <div className="space-y-2">
                      <div className="text-sm font-semibold">输入参数:</div>
                      <div className="bg-muted p-3 rounded-md">
                        <pre className="text-xs overflow-x-auto">
                          {JSON.stringify(tool.inputSchema, null, 2)}
                        </pre>
                      </div>
                    </div>
                  </CardContent>
                )}
              </Card>
            );
          })}
        </div>
      )}

      {/* Tool Count */}
      {tools.length > 0 && (
        <div className="text-sm text-muted-foreground text-center">
          共 {tools.length} 个工具
        </div>
      )}
    </div>
  );
}
